package OliveWindow;

# Copyright (c) 2005, Shawn Boyette
# All rights reserved.
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, provided
# that the above copyright notice(s) and this permission notice appear
# in all copies of the Software and that both the above copyright
# notice(s) and this permission notice appear in supporting
# documentation.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR
# ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY
# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
# OF THIS SOFTWARE.
#
# Except as contained in this notice, the name of a copyright holder
# shall not be used in advertising or otherwise to promote the sale,
# use or other dealings in this Software without prior written
# authorization of the copyright holder.

require Exporter;
use warnings;
use strict;

our @ISA       = qw(Exporter);
our @EXPORT    = qw( &wininit &winflip &winstatus &winstatmsg &winredraw );

#######################################################################
##  window and system logic  ##########################################
#######################################################################

sub linklist {
   my $cui = shift;
   my $d   = $cui->userdata->{dbh};
   my $sid = $cui->userdata->{sid};
   my $w = $cui->userdata->{wins};

   if($cui->getobj('linkl')) {
       $cui->getobj('linkl')->focus;
       $cui->getobj('linkl')->draw;
       return;
   }

   my ($count) = $d->selectrow_array("SELECT count(sid) FROM links WHERE sid = $sid");
   return unless $count;

   my @links = ();
   my %descs = ();
   my $maxheight = int($w->{dim}[1] / 2);
   my $height    = 0;
   my $width     = 0;
   my $i         = 0;

   my $statement = "SELECT link, desc FROM links WHERE sid = $sid ORDER BY num";
   my $sth = $d->prepare($statement);
   $sth->execute;

   while (my $q = $sth->fetchrow_arrayref) {
       $links[$i] = $q->[0];
       $q->[1] = substr($q->[1],0,32) . '...' if (length($q->[1]) >= 40);
       $q->[1] = sprintf("[%2d] %s",$i,$q->[1]);
       while (defined $descs{$links[$i]}) {
           # pad with spaces to make links unique (is this bad?)
           $links[$i] = join('',$links[$i],' ');
       }
       $descs{$links[$i]} = $q->[1];

       my $len = length($q->[1]);
       $width = $len if ($len > $width);
       $i++;
   }
   
   $height = ($i < $maxheight - 6) ? ($i + 6) : $maxheight;
   my $winwidth = $width + 5;
   $winwidth = 15 if ($winwidth < 14);

   my $ll = $cui->add('linkl', 'Window',
                      -border   => 1,
                      -bfg      => 'blue',
                      -height   => $height,
                      -width    => $winwidth,
                      -title    => 'Linklist',
                      -centered => 0,
                      -y        => 0,
                      -x        => $w->{dim}[0] - $winwidth + 1,
       );
    $ll->{list} = $ll->add('llli', 'Listbox',
                           -values => \@links,
                           -labels => \%descs,
                           -height => $height - 6,
                           -width  => $width + 2,
                           -y      => 1,
                           -x      => 1,
                           -vscrollbar => 1,
                           -onchange   => sub { &OliveMisc::followlink($cui,$ll->{list}->get) },
        );
   $ll->{okb} = $ll->add('llok', 'Buttonbox',
                         -y       => -2,
                         -x       => $winwidth - 13,
                         -buttons => [ { -label   => '< Cancel >',
                                         -value   => 1,
                                         -onpress => sub { $ll->loose_focus;
                                                           $cui->enable_timer('clock');
                                                           $cui->delete('linkl');
                                                           $cui->draw },
                                       }
                         ],
       );
    if ($cui->userdata->{c}->{gsp}) {
        $ll->set_binding( sub { $w->{story}{view}->cursor_pagedown; 
                                $w->{story}{view}->draw; }, $cui->userdata->{keys}->{gpdn} );
        $ll->set_binding( sub { $w->{story}{view}->cursor_pageup;
                                $w->{story}{view}->draw; }, $cui->userdata->{keys}->{gpup} );
    }

    $cui->disable_timer('clock');
    $ll->draw;
    $ll->focus;
}

sub winflip {
    my $cui = shift;
    my $c   = $cui->userdata->{c};
    my $focus = 0;

    if ($_[0] && ($_[0] eq 'story' or $_[0] eq 'news')) {
        $focus = $_[0];
    } else {
        $focus = $cui->userdata->{focus};
    }

    my $w   = $cui->userdata->{wins};
    my $msg = '';

    if ($focus eq 'news') {
        $w->{news}{ftr2}->text('V');
        $w->{news}{ftr2}->draw;
        $msg = $cui->userdata->{chan} if $cui->userdata->{chan};
        $w->{news}{ftr1}->text($msg . ' ' x ($w->{dim}[0] - length($msg)));
        $w->{news}{ftr1}->draw;
        $w->{story}{view}->focus;
        $cui->userdata->{focus} = 'story';
    } else {
        $w->{news}{ftr2}->text('^');
        $w->{news}{ftr2}->draw;
        $msg = $cui->userdata->{stat} if ($cui->userdata->{stat} && $c->{sls});
        $w->{news}{ftr1}->text($msg . ' ' x ($w->{dim}[0] - length($msg)));
        $w->{news}{ftr1}->draw;
        $w->{news}{list}->focus;
        $cui->userdata->{focus} = 'news';
    }
}

sub wininit {
    my ($cui,$root) = @_;
    my $c = $cui->userdata->{c};
    my %w = ();

    my $height = $root->height;
    my $width  = $root->width - 1;
    my $r = $height % 2;
    my $title = "Olive " . $cui->userdata->{rel};
    $w{dim}[0] = $width;
    $w{dim}[1] = $height;
    $w{dim}[2] = $r;

    $w{news} = $root->add('news', 'Window',
                          -border => 0,
                          -height => int($height / 2),
                         );
    $w{news}{head} = $w{news}->add('header', "Label",
                                   -bg   => 'blue',
                                   -fg   => 'white',
                                   -text => $title . (' ' x ($width - length($title) + 1)),
                                   -bold => 1,
                                  ) unless $c->{dst};
    $w{news}{ftr1} = $w{news}->add('footer1', "Label",
                                   -bg    => 'blue',
                                   -text  => ' ' x $width,
                                   -width => $width,
                                   -y     => int($height / 2) - 1,
                                   -bold => 1,
                                  );
    $w{news}{ftr2} = $w{news}->add('footer2', "Label",
                                   -bg    => 'blue',
                                   -bold  => 1,
                                   -text  => '^',
                                   -width => 1,
                                   -x     => $width,
                                   -y     => int($height / 2) - 1,
                                  );

    $w{story} = $root->add( 'story', 'Window',
                            -border => 0,
                            -height => int($height / 2) + $r,
                            -y => int($height / 2),
                          );
    $w{story}{view} = $w{story}->add('storyview', 'TextViewer',
                                     -wrapping   => 1,
                                     -text       => "",
                                     -vscrollbar => 1,
        );
    return \%w;
}

sub winredraw {
    my ($cui,$root) = @_;
    my $sel = $cui->userdata->{wins}->{news}{list}->get_active_id;
    $cui->userdata->{nlsel} = $sel || '0E0';
    
    $root->delete('news');
    $root->delete('story');
    $cui->layout;

    $cui->userdata->{wins} = wininit($cui,$root);
    &OliveFeed::refreshlist($cui);
    &OliveStory::storypick($cui);
    $cui->userdata->{nlsel} = 0;
}

sub winstatus {
    my $cui = shift;

    return if $cui->userdata->{shift};

    my $w   = $cui->userdata->{wins};
    my $msg = '';

    my $cur = $w->{news}{list}->get_active_id + 1;
    my $max = $w->{news}{list}->{-max_selected} + 1;
    $cur = ($cur < 1) ? 1 : $cur;       # keep PgUp/PgDn from making $cur less than one
    $cur = ($cur > $max) ? $max : $cur; # or more than the max possible story

    my $ur  = $cui->userdata->{ur};
    my $new = $cui->userdata->{new};
    
    $msg = "[S: $cur/$max] [U/N: $ur/$new] ".$cui->userdata->{poll};
    if ($cui->userdata->{star} || $cui->userdata->{flag}) {
        $msg .= ' [F: ';
        $msg .= 'F' if $cui->userdata->{flag};
        $msg .= ',' if ($cui->userdata->{flag} && $cui->userdata->{star});
        $msg .= 'S' if $cui->userdata->{star};
        $msg .= ']';
    }
    $cui->userdata->{stat} = $msg;

    $w->{news}{ftr1}->text(join('',$msg,(' ' x ($w->{dim}[0] - length($msg)))));
    $w->{news}{ftr1}->draw;
}


sub winstatmsg {
    my ($cui,$msg) = @_;
    my $w = $cui->userdata->{wins};
    $w->{news}{ftr1}->text(join('',$msg,(' ' x ($w->{dim}[0] - length($msg)))));
    $w->{news}{ftr1}->draw;
}


1;
